from emmodels.em_base_data import BaseData
from emmodels.em_his_series import HisSeries
from emutils.time_utils import get_offset_day
import tushare as ts
import datetime
# 首先查询股票基本信息表，维持一个字典{'id':'stkcode'},同时存放一个list
# 然后依次pop 这个list里面的item, 对每个item 从 tushare上 查询
# 最后插入,不需要从code映射回去，直接就拿stkcode作为key


base_datas = BaseData.select_all()
m = 0
print('开始插入')
l = []

def sys_all():

    for i in range(len(base_datas)):
        item = base_datas[i]
        begin_time = datetime.datetime.now()
        print('插入第%d条数据，共需要插入%d条数据' % (i, len(base_datas)))

        stkCode = item.stkcode
        ipodate = item.ipodate
        stkname = item.stkname

        if ipodate == None:
            print("新股未上市")
            continue
        if stkCode == None:
            continue
        last_his = HisSeries.select_last(stkCode)
        start_date = None
        if last_his and last_his.datatime:
            start_date = min(last_his.datatime, datetime.datetime.now())
        else:
            start_date = ipodate

        end_date = datetime.datetime.now()

        l = _sys_stk_his(start_date, end_date, stkCode, ipodate)

        # t = ts.get_k_data(code=stkCode,start=start,end=end,pause=1,ktype='60', autype='qfq')
        # his_series = [HisSeries(stockid=stkCode,datatime=his[0],open=his[1],close=his[2],high=his[3],low=his[4],volume=his[5],period='60') for his in t.values]
        # l.extend(his_series)

        if len(l) >0:
            HisSeries.insert_list(l,append_dup_list=['stockid', 'datatime', 'period'])
            print('插入%s(%s)所有从%s到%s这段时间周期数据,耗时%d秒' % (stkname, stkCode, start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'),
                                                      (datetime.datetime.now() - begin_time).seconds))
        else:
            print("无数据同步")
        l.clear()
    print('插入完成')

def sys_stk_from_ipodate(stk_code,fetchall=False):
    base_data = BaseData.select_stkcode(stkcode=stk_code)
    if base_data:
        stkCode = base_data.stkcode
        ipodate = base_data.ipodate
        stkname = base_data.stkname
        _sys_stk_his(stk_code, ipodate)

    pass

def _sys_stk_his(start_date, end_date, stkCode=None,ipodate=None):

    start = start_date.strftime('%Y-%m-%d')
    # start = '2016-01-01 09:00'
    end = end_date.strftime('%Y-%m-%d')
    # end = '2016-11-01 16:00'

    m1 = ts.get_k_data(code=stkCode, start=start, end=end, pause=0.1, ktype='M', autype='qfq')
    m_his_series = [
        HisSeries(stockid=stkCode, datatime=his[0], open=his[1], close=his[2], high=his[3], low=his[4], volume=his[5],
                  period='M') for his in m1.values]
    l.extend(m_his_series)

    w1 = ts.get_k_data(code=stkCode, start=start, end=end, pause=0.1, ktype='W', autype='qfq')
    w_his_series = [
        HisSeries(stockid=stkCode, datatime=his[0], open=his[1], close=his[2], high=his[3], low=his[4], volume=his[5],
                  period='W') for his in w1.values]
    l.extend(w_his_series)

    d1 = ts.get_k_data(code=stkCode, start=start, end=end, pause=0.1, ktype='D', autype='qfq')
    d_his_series = [
        HisSeries(stockid=stkCode, datatime=his[0], open=his[1], close=his[2], high=his[3], low=his[4], volume=his[5],
                  period='D') for his in d1.values]
    l.extend(d_his_series)
    return l


sys_all()